var Events = require('ym-Events')
cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {
        enemys :[cc.SpriteFrame],
        countIcon:[cc.SpriteFrame],
        sup:[cc.SpriteFrame],
        supIcon1:cc.Sprite,
        supIcon2:cc.Sprite,
        moveBtn:cc.Node,
        videoOrShare:[cc.SpriteFrame],
        star:require('ShowStar')
    },

    onLoad(){
        this._super();
        this.coin=0;
        Events.on('wechatMenuClose',this.enterMain.bind(this),this)
        Events.on('wechatMenuOpen',this.closeBanner.bind(this),this)
        // var rc = require('RewardComponent');
        // this.has = rc.hasVideo();//是否能看视频
        this.enemyIcon= cc.find('view/result/layout/panel/enemy/plane',this.node).getComponent(cc.Sprite);//战胜敌机图片
        this.enemyCount= cc.find('view/result/layout/panel/enemy/enemyCount',this.node).getComponent(cc.Label);//战胜敌机数量
        this.coinNumber= cc.find('view/result/layout/panel/enemy/coinNumber',this.node).getComponent(cc.Label);//战胜敌机获得的金币
        this.title=cc.find('view/result/title',this.node);//结束title
        this.reward=cc.find('view/result/layout/panel/coin/number',this.node).getComponent(cc.Label);//过关奖励金币数量
        this.allReward=cc.find('view/result/reward/coinNumber',this.node).getComponent(cc.Label);//过关总奖励
        this.allRewardTriple=cc.find('view/result/layout/triple/coinNumber',this.node).getComponent(cc.Label);//过关总奖励
        this.shareVideo=cc.find('view/result/layout/triple/sanbeilingqu',this.node).getComponent(cc.Sprite);

        this.supPanel= cc.find('view/result/layout/panel/sup',this.node);//副武器
        this.rewardNumber=0;
        this.getCoin = 0;//获得的总金币数量
        // if(this.has){
        //     this.shareVideo.spriteFrame = this.videoOrShare[0]
        // }else{
        //     this.shareVideo.spriteFrame = this.videoOrShare[1]
        // }
        this.rewardFirst=true;
        this.showFriendLink();
        this.relifeTime=5;//复活确定时间
        this.jumpButton = null
    },

    start(){
        Events.on('banner_show',this.onBannerShow,this)
    },
    onBannerShow(res){
        var systemInfo = wx.getSystemInfoSync();
        let y = -cc.winSize.height / 2 + res.height / systemInfo.screenHeight * cc.winSize.height;
        if(this.jumpButton){
            this.scheduleOnce(()=>{
                this.jumpButton.y = -330
            },0.3)
        }
    },
    onDestroy(){
        global.BannerAD.destroy();
        Events.removeAllListeners(this)
    },

    closeBanner(){
        global.BannerAD.destroy();
    },

    enterMain(){
        if(global.gates=='1-1' && this.result){
            this.httpGet('/game/gameUser','channelEvent.add',{eventName:'过第一关'},function(err,res){
            })
        }
        if(global.gates=='1-1' && !this.result){
            this.httpGet('/game/gameUser','channelEvent.add',{eventName:'未过第一关'},function(err,res){
            })
        }
        global.Data.prop2=false;
        global.usedFu=false;
        global.usedFullLevel=false;
        global.EJMgr.popUI();
        global.GameLoop.enterSelectPlane();
    },

    setOptions(option){
        if(global.canRelife){
            cc.find('WechatMenu',this.node).active=false
        }
        if(!!global.usedFu && !option.result){
           option.score=Math.ceil(200*(global.Data.mainArmsLevel+1)*Math.pow(1.2,global.Data.mainArmsLevel))+Math.ceil(200*(global.Data.mainArmsLevel+2)*Math.pow(1.2,global.Data.mainArmsLevel+1))+Math.ceil(200*(global.Data.mainArmsLevel+3)*Math.pow(1.2,global.Data.mainArmsLevel+2))
        }
        cc.find('view/result/star',this.node).active=false
        cc.find('view/result/title',this.node).active=false
        cc.find('view/resultLast',this.node).active=false
        cc.find('view/relife/time',this.node).getComponent(cc.Sprite).spriteFrame=this.countIcon[this.relifeTime];
        cc.log('option:',option)
        cc.find('view/resultLast/getCoin/number',this.node).getComponent(cc.Label).string=global.Common.getKV(option.score)
        this.option = option;
        this.supPanel.active=false;
        this.result=option.result;
        this.title.children[0].active=option.result;
        this.title.children[1].active=!option.result;
        global.lastGameResult = this.result;
        cc.find('view/result',this.node).active = option.result || !global.canRelife;

        SoundMgr.stopMusic()
        if(option.result){
            SoundMgr.playSound('Audio/win')
        }else{
            SoundMgr.playSound('Audio/loss')
        }

        
        if(global.gates=='1-1' && option.result){
            this.httpGet('/game/gameUser','channelEvent.add',{eventName:'过第一关'},function(err,res){
                cc.log('=========',res)
            })
        }


        cc.find('view/show',this.node).active = false
        cc.find('view/relife',this.node).active = !option.result && global.canRelife;

        this.enemyCount.string='X'+global.enemyCount;
        this.coinNumber.string=Math.floor(option.score);
        if(global.gates!=0 ){
            cc.find('view/result/star',this.node).active=true
            global.tryFullLevel=!option.result;
            var number=Math.floor((parseInt(global.gates.split('-')[0])-1)*4+parseInt(global.gates.split('-')[1])-1)
            this.enemyIcon.spriteFrame = this.enemys[number>7?7:number];
            if(option.result){
                this.star.runStar(3-global.regameCount);
                // this.supPanel.active=true;
                var icon=Math.floor((parseInt(global.gates.split('-')[0])-1)*4+parseInt(global.gates.split('-')[1]))
                this.supIcon1.spriteFrame=this.sup[icon]
                this.supIcon2.spriteFrame=this.sup[icon]
                cc.sys.localStorage.setItem('usedSup',icon)
            }
        }else{
            cc.find('view/result/title',this.node).active=true
        }
        

        option.result && (this.rewardNumber = option.coin);
        
        this.reward.string=this.rewardNumber;
        this.getCoin=Math.floor(option.score);
        this.allReward.string=global.Common.getKV(this.getCoin);
        this.allRewardTriple.string=global.Common.getKV(this.getCoin*3);;

        cc.find('view/showFull',this.node).active=false;
        if(!option.result && global.canRelife){
            this.showRelifeFriend();
            var count=cc.find('view/relife/time',this.node);
            count.runAction(cc.sequence(cc.scaleTo(0.7,1.3),cc.scaleTo(0.3,1)))
            this.title.children[0].active=option.result;
            this.title.children[1].active=!option.result;
            this.daojishi=()=>{
                count.runAction(cc.sequence(cc.scaleTo(0.7,1.3),cc.scaleTo(0.3,1)))
                count.getComponent(cc.Sprite).spriteFrame=this.countIcon[this.relifeTime-1];
                this.relifeTime--;
                if(this.relifeTime == 1){
                    global.BannerAD.destroy();
                }
            }
            this.schedule(this.daojishi,1,this.relifeTime);
            
            this.scheduleOnce(()=>{
                cc.find('WechatMenu',this.node).active=true
                this.showResult()
            },this.relifeTime+1)
            global.BannerAD.createBanner('adunit-0a087d278c557c37');
        } else if(option.result){
            this.moveBtn.active = false;
            this.moveBtn = cc.find('view/result/uplevel',this.node)
            this.moveBtn.active = true;
            this.moveBanner();
            this.jumpButton = cc.find('view/result/fangqi',this.node)
            console.log('jumpButton:',this.jumpButton)
            // global.BannerAD.createBanner('adunit-0a087d278c557c37');
        }
        else{
            this.showResult();
        }
        if(global.gates==0){
            // option.result=true;
            CC_WECHATGAME&&wx.postMessage({
                messageType : 1,
                openType : wx.RankKey,
                score : Math.floor(option.score)
            })
        }else{
            CC_WECHATGAME&&wx.postMessage({
                messageType : 6,
                openType : wx.LevelKey,
                plotId :global.Data.currentPass,
                score : Math.floor(option.score)
            })
        }
        
    },

    clickLast(){
        if(global.gates=='1-1'){
            this.httpGet('/game/gameUser','channelEvent.add',{eventName:"未过第一关"},function(err,res){
                cc.log('=========',res)
            })
        }
        var self=this;
        var options={
                adUnitId:'adunit-6ca9f0f26ddc27cd',
                stopCb:function(){
                    global.EJMgr.showToast('视频未看完，不能获得奖励')
                },
                successCb:function(){
                    self.rewardCoin(self.option.score)
                }
            }
        global.WechatShare.videoOrShare(options)
    },

    showResult(){

        cc.find('view/relife',this.node).active = false;
        if(global.gates=='0'){
            cc.find('view/result',this.node).active = true;
            cc.find('view/result/layout',this.node).active=true;
            cc.find('view/result/layout/triple',this.node).active=true;
            cc.find('view/result/reward',this.node).active=true;
            cc.find('view/result/uplevel',this.node).active=false;
            return
        }
        global.firstResult++
        if(!!global.usedFu){
            cc.find('view/result',this.node).active = false;
            cc.find('view/show',this.node).active=false;
            cc.find('view/resultLast',this.node).active=true;
            if(global.Data.isCheck) return;
            // this.scheduleOnce(()=>{
            //     cc.find('view/result/uplevel',this.node).y=-100;
            //     var p = -210 + cc.winSize.height / 2 
            //     if(CC_WECHATGAME){
            //         global.BannerAD.moveBanner(0,p);
            //     }
            // },1)
            return
        }
        
        if(global.canRelife){//携带道具
            cc.find('view/result',this.node).active=false;
            cc.find('view/show',this.node).active=true;
            cc.find('view/showFull',this.node).active=false;
            this.jumpButton = cc.find('view/show/fangqi',this.node)
            this.moveBanner();
        }else if(!global.canRelife){//满级试用
            global.usedFu=true;
            global.canRelife=true;
            global.BannerAD.destroy();
            cc.find('view/result',this.node).active=false;
            cc.find('view/show',this.node).active=false;
            cc.find('view/showFull',this.node).active=true;
        }
        var p = -371 + cc.winSize.height / 2 
        if(!CC_WECHATGAME) return
        // this.scheduleOnce(()=>{
        //     if(global.Data.isCheck) return;
        //     global.BannerAD.moveBanner(0,p);
        // },1)
        
        
    },

    restartGame(e,d){
        var self=this;
        function joinGame(){ 
            let sound=global.gates==0?'wujin':global.gates.split('-')[0];
            SoundMgr.playMusic('./Audio/bgm_'+sound)
            SoundMgr.playSound('Audio/count');
            global.GameLoop.GameMgr.onRelife();
            global.EJMgr.popUI();
        }
        var options={};
        if(d=='xiedai'){
            global.Data.prop2=true;
            global.Data.prop=[true,true,true]
            options={
                adUnitId:'adunit-21fe2ed90bd8b24d',
                stopCb:function(){
                    global.EJMgr.showToast('视频未看完，不能获得奖励')
                },
                successCb:function(){
                    if(self.node){
                        global.regameCount++
                        joinGame()
                    }
                }
            }
        }
        if(d=='try'){
            global.Data.prop2=false;
            global.usedFullLevel=true;
            global.planeId=2;
            options={
                adUnitId:'adunit-6ca9f0f26ddc27cd',
                stopCb:function(){
                    global.EJMgr.showToast('视频未看完，不能获得奖励')
                },
                successCb:function(){
                    if(self.node){
                        global.regameCount++
                        joinGame()
                    }
                    
                }
            }
        }
        global.WechatShare.videoOrShare(options)
    }, 

    outGame(){
        
        if(global.gates=='1-1'){
            this.httpGet('/game/gameUser','channelEvent.add',{eventName:"未过第一关"},function(err,res){
                cc.log('=========',res)
            })
        }

        global.Data.prop2=false;
        global.usedFu=false;
        global.usedFullLevel=false;
        global.EJMgr.popUI();
        global.GameLoop.enterSelectPlane();
    },


    moveBanner(){
        console.log('moveBanner:',global.Data.isCheck)
        // if(!global.Data.isCheck){
        this.scheduleOnce(()=>{
            global.BannerAD.createBanner('adunit-0a087d278c557c37');
        },0.8);

        if(global.Data.isCheck && this.jumpButton){
            this.jumpButton.opacity = 0;
            this.scheduleOnce(()=>{
                this.jumpButton.opacity = 255
            },1.5)
        }
        // }
    },

    rewardCoin(number){


        this.httpGet('/game/gameUser','attrAdd',{propName: "goldCoin",count: number},function(err,res){
            if(!err){
                global.Data.goldCoin += number;
                global.EJMgr.showToast('获取金币成功');

                
                global.BannerAD.destroy();
                if(global.gates!=0){
                    global.usedFullLevel=false;
                }
                global.usedFu=false;
                global.Data.prop2=false;
                global.EJMgr.popUI();
                global.GameLoop.enterSelectPlane();
            }
        })

    },

    showFriendLink(){
        if(!global.Data.friendlyLinks){
            return
        }
        // function bottom(element) {
        //     return element.sceneName == '游戏结束';
        // }
        // var arr = global.Data.friendlyLinks.filter(bottom);

        // var friend=cc.find('view/result/friendLink',this.node);
        // var friend2=cc.find('view/show/friendLink',this.node);
        // var friend3=cc.find('view/showFull/friendLink',this.node);
        // var friend4=cc.find('view/resultLast/friendLink',this.node);
        // friend.active=true;
        // friend2.active=true
        // for(let i=0;i<friend.children.length;i++){
        //     if(arr[i]){
        //         friend.children[i].getComponent('FriendlyLink').setOptions(arr[i]);
        //         friend2.children[i].getComponent('FriendlyLink').setOptions(arr[i]);
        //         friend3.children[i].getComponent('FriendlyLink').setOptions(arr[i]);
        //         friend4.children[i].getComponent('FriendlyLink').setOptions(arr[i]);
        //         if(i%2===0){//skewTo
        //             friend.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //             friend2.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //             friend3.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //             friend4.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //         }else{
        //             friend.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //             friend2.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //             friend3.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //             friend4.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //         }
        //     }else{
        //         friend.children[i].active=false
        //         friend2.children[i].active=false
        //         friend3.children[i].active=false
        //         friend4.children[i].active=false
        //     }
            
        // }
    },

    showRelifeFriend(){
        if(!global.Data.friendlyLinks){
            return
        }

        function bottom(element) {
            return element.sceneName == '复活';
        }
        var arr = global.Data.friendlyLinks.filter(bottom);

        var friend=cc.find('view/relife/friendLink',this.node);
        friend.active=true
        for(let i=0;i<friend.children.length;i++){
            if(arr[i]){
                friend.children[i].getComponent('FriendlyLink').setOptions(arr[i]);
            }else{
                friend.children[i].getComponent('FriendlyLink').setOptions(arr[i-3]);
            }
            
            if(i%2===0){//skewTo
                friend.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
            }else{
                friend.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
            }
        }
    },

    clickReward(){//普通领取
        if(this.rewardFirst){
            SoundMgr.playButtonEffect();
            this.rewardCoin(this.getCoin);
        }
        
    },
    clickTriple(){//三倍领取
        SoundMgr.playButtonEffect();
        var self=this;
        if(!this.rewardFirst){return}
        self.rewardFirst=false;
        var options={
            adUnitId:'adunit-3272773a885b41c6',
            stopCb:function(){
                self.rewardFirst=true;
                console.log('看视频失败',self.rewardFirst)
                global.EJMgr.showToast('看完视频才能获得三倍奖励')
            },
            successCb:function(){

                if(self.node){
                    self.rewardCoin(self.getCoin*3);
                }
            }
        }
        global.WechatShare.videoOrShare(options)
    },
    clickrelife(){//复活
        SoundMgr.playButtonEffect();
        var self=this;
        this.unscheduleAllCallbacks();
        // cc.find('view/relife',self.node).active = false
        var options={
            adUnitId:'adunit-e5b123e84355d491',
            stopCb:function(){
                global.EJMgr.showToast('视频未看完，不能复活');
                self.setOptions(self.option);
            },
            successCb:function(){
                
                if(self.node){
                    global.regameCount++
                    global.canRelife = false;
                    let sound=global.gates==0?'wujin':global.gates.split('-')[0];
                    SoundMgr.playMusic('./Audio/bgm_'+sound)
                    SoundMgr.playSound('Audio/count');
                    global.GameLoop.GameMgr.onRelife();
                    global.EJMgr.popUI();
                }
            }
        }
        global.WechatShare.videoOrShare(options)
    },
    onClickUpLevel(){
        var self = this;
        global.usedFu=false;
        global.usedFullLevel=false;
        global.Data.prop2=false;
        let number=0;
        function uplevel(){
            for(let i=0;i<2;i++){
                self.scheduleOnce(()=>{
                    self.httpGet('/game/gameUser',"attrLevelUp",{propName: 'mainArmsLevel',goldCoinCount: 0},function(err,res){
                        if(!err){
                            global.Data.mainArmsLevel++;
                            self.httpGet('/game/gameUser',"attrLevelUp",{propName: 'speedLevel',goldCoinCount: 0},function(err,res){
                                if(!err){
                                    number++;
                                    global.Data.speedLevel++;
                                    global.EJMgr.showToast('升级成功')
                                    if(number===2){
                                        global.BannerAD.destroy();
                                        global.EJMgr.popUI();
                                        global.GameLoop.enterSelectPlane();
                                    }
                                }else{
                                    global.EJMgr.showToast('升级失败')
                                    global.BannerAD.destroy();
                                    global.EJMgr.popUI();
                                    global.GameLoop.enterSelectPlane();
                                }
                            });
                        }else{
                            global.EJMgr.showToast('升级失败')
                            global.BannerAD.destroy();
                            global.EJMgr.popUI();
                            global.GameLoop.enterSelectPlane();
                        }
                    });
                },i*0.5)
            }
        }
        if(CC_WECHATGAME){
            var options={
                adUnitId:'adunit-e5b123e84355d491',
                stopCb:function(){
                    global.EJMgr.showToast('视频未看完，不能升级');
                    self.setOptions(self.option);
                },
                successCb:uplevel
            }
            global.WechatShare.videoOrShare(options)
        } else { 
            uplevel();
        }   
    }
});
